package com.gree.yipai.base;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gree.yipai.Const;
import com.gree.yipai.R;
import com.gree.yipai.activity.LoginActivity;
import com.gree.yipai.server.APIAction;
import com.gree.yipai.server.bean.IntentKV;
import com.gree.yipai.server.network.async.AsyncTaskManager;
import com.gree.yipai.server.network.async.OnDataListener;
import com.gree.yipai.server.network.http.HttpException;
import com.gree.yipai.server.response2.Respone;
import com.gree.yipai.server.utils.CommonUtils;
import com.gree.yipai.server.utils.FileUtil;
import com.gree.yipai.server.utils.NLog;
import com.gree.yipai.server.utils.NToast;
import com.gree.yipai.server.utils.SharedPreferencesUtil;
import com.gree.yipai.server.utils.json.JsonMananger;
import com.gree.yipai.utils.ActivityCollector;

import java.util.Date;


/**
 *  基fragment
 *  继承此类免去一些初始化
 *  注意：子类创建view要使用这个方法
 *   View view = super.onCreateView(inflater,container,savedInstanceState);
 *   setContentView(R.layout.activity_layout);
 */
public abstract class BaseFragment extends Fragment implements OnDataListener {

    protected Context mContext;
    public AsyncTaskManager mAsyncTaskManager;
    protected APIAction action;
    public View baseView;
    private ViewFlipper mContentView;
    /**
     * 是否有网
     */
    protected boolean onNet;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        baseView = inflater.inflate(R.layout.activity_base, container, false);
        mContentView =  baseView.findViewById(R.id.layout_container);
        mContext = getActivity();
        //异步线程、事件相关
        mAsyncTaskManager = AsyncTaskManager.getInstance(mContext);
        // Activity管理
        action = new APIAction(mContext);
        String token = getData(Const.TOKEN,null);
        if(token!=null){
            action.setToken(token);
        }
        onNet = CommonUtils.isNetworkConnected(mContext);
        return baseView;
    }


    @Override
    public void onResume() {
        super.onResume();
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    public void setContentView(View view) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1);
        mContentView.addView(view, lp);
    }

    public void setContentView(int layoutResID) {
        View view = LayoutInflater.from(mContext).inflate(layoutResID, null);
        setContentView(view);
    }



    /**
     * 发送请求（需要检查网络）
     *
     * @param requestCode 请求码
     */
    public void request(int requestCode) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(requestCode, this);
        }
    }


    /**
     * 发送请求（需要检查网络）
     *
     * @param id 请求数据的用户ID或者groupID
     * @param requestCode 请求码
     */
    public void request(String id , int requestCode) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(id, requestCode, this);
        }
    }

    /**
     * 发起请求 并把Uri转为path
     * @param uri
     * @param requestCode
     */
    public void request(Uri uri,int requestCode){
        String filepath = FileUtil.getPath(mContext,uri);
        request(filepath,requestCode);
    }
    /**
     * 发送请求
     *
     * @param requestCode    请求码
     * @param isCheckNetwork 是否需检查网络，true检查，false不检查
     */
    public void request(int requestCode, boolean isCheckNetwork) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(requestCode, isCheckNetwork, this);
        }
    }

    /**
     * 取消所有请求
     */
    public void cancelRequest() {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.cancelRequest();
        }
    }

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        return null;
    }

    private int errCount = 0 ;

    @Override
    public void onSuccess(final int requestCode, Object result) {
        if(result instanceof Respone){
            Respone respone = (Respone)result;
            if(respone.getStatusCode()==401){
                errCount++;
                Long dates = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN_EXPIRES_TIME,0l);
                if(dates>0){
                    Date date = new Date(dates);
                    //NLog.e("extend_token",DateUtil.format(date,null),new Date().after(date));
                    if(new Date().before(date)){
                        boolean should = putData(Const.SHOULD_REFRESH_TOKEN,false);
                        if(!should){
                            putData(Const.SHOULD_REFRESH_TOKEN,true);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    request(requestCode);
                                }
                            },2000);
                        }
                    }else{
                        shouldLoginOut();
                    }
                }
            }
        }

    }

    @Override
    public void onFailure(final int requestCode, int state, Object result) {
        if(result instanceof Respone){
            Respone respone = (Respone)result;
            if(respone.getStatusCode()==401){
                Long dates = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN_EXPIRES_TIME,0l);
                if(dates>0){
                    Date date = new Date(dates);
                    //NLog.e("extend_token",DateUtil.format(date,null),new Date().after(date));
                    if(new Date().before(date)){
                        boolean should = putData(Const.SHOULD_REFRESH_TOKEN,false);
                        if(!should){
                            putData(Const.SHOULD_REFRESH_TOKEN,true);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    request(requestCode);
                                }
                            },2000);
                        }
                    }else{
                        shouldLoginOut();
                    }
                }
            }
        }
        //做些请求失败的处理，如果不想用这些处理方式可以在子类中不使用super.onFailure
        switch (state) {
            case AsyncTaskManager.REQUEST_CREATE_CODE:
                shortToast( "创建成功");
                break;
            case AsyncTaskManager.REQUEST_DATA_ERROR_CODE:
                shortToast( "提交数据不合法,请检查");
                break;
            case AsyncTaskManager.REQUEST_FORBIDDEN_CODE:
                shortToast( "无权限访问");
                break;
            case AsyncTaskManager.REQUEST_NOTPAGE_CODE:
                shortToast( "当前API接口已失效");
                break;
            case AsyncTaskManager.REQUEST_DECODE_CODE:
                shortToast( "数据解析异常！");
                break;
            case AsyncTaskManager.REQUEST_ERROR_CODE:
                shortToast( "数据请求异常！");
                break;
            case AsyncTaskManager.RESPONE_ERROR_CODE:
                shortToast( "很抱歉当前服务器故障，请稍后重试！");
                break;
            case AsyncTaskManager.HTTP_TIMEOUT_CODE:
                shortToast( "网络请求超时，请重试!");
                break;
            case AsyncTaskManager.HTTP_ERROR_CODE:
                shortToast( "网络请求异常，请重试!");
                break;
            case AsyncTaskManager.HTTP_NULL_CODE:
                shortToast( "当前网络不可用");
                break;

        }
        if(result instanceof Exception) {
            Exception e = (Exception) result;
            Log.e("onFailure", e.getMessage());
        }
    }

    /**
     * 网络断开监听
     */
//    @Override
//    public void onNetDisconnected() {
//        onNet = false;
//        Log.i("onNetDisconnected","断网了...");
//    }

    /**
     * 网络连接上监听
     * @param networkType
     */
//    @Override
//    public void onNetConnected(NetworkType networkType) {
//        onNet = true;
//        Log.i("onNetConnected","有网了..."+networkType.name());
//    }
    /**
     * 退出
     */
    public void loginOut(){
        //清空任务栈
        startActivity(LoginActivity.class);
        ActivityCollector.finishAll();
    }


    public void shouldLoginOut(){
        shouldLoginOut("您的账号长时间未操作，为保证安全请重新登录!");
    }
    //强制退出
    public void shouldLoginOut(String info){
        //清空任务栈
        startActivity(LoginActivity.class, IntentKV.set(info));
        ActivityCollector.finishAll();
    }

    /**
     * 提示
     * @param msg
     */
    public void shortToast(String msg){
        NToast.shortToast(mContext,msg);
    }

    public void longToast(String msg){
        NToast.longToast(mContext,msg);
    }

    /**
     *
     * @param json
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(String json, Class<T> cls) {
        try {
            return JsonMananger.jsonToBean(json,cls);
        }catch (Exception e){
            Log.e("jsonToBean",e.getMessage());
        }
        return null;
    }

    /**
     *
     * @param obj
     * @return
     * @throws HttpException
     */
    public static String beanToJson(Object obj){
        try {
            return JsonMananger.beanToJson(obj);
        }catch (Exception e){
            Log.e("beanToJson",e.getMessage());
        }
        return null;
    }



    /**
     * 打开并关闭当前
     * @param cla
     * @param obj
     */
    public void startActivityAndFinish(Class cla,Object ...obj){
        startActivity(cla,obj);
        getActivity().finish();
    }
    private long times;
    /**
     * 打开页面
     * @param cla
     * @param obj 参数名称ext_{i},intentKV 只能传int float String
     */
    public void startActivity(Class cla,Object ...obj){
        if(System.currentTimeMillis()-times<=1000){
            return;
        }
        times = System.currentTimeMillis();
        Intent intent = CommonUtils.getIntent(obj);
        intent.setClass(mContext,cla);
        startActivity(intent);
    }

    /**
     * 打开有回调的页面
     * @param cla
     * @param requestCode
     * @param obj 参数名称ext_{i},intentKV 只能传int float String
     */
    public void startActivityWidthResult(Class cla, int requestCode, Object ...obj){
        NLog.d("startActivityWidthResult",System.currentTimeMillis()-times);
        if(System.currentTimeMillis()-times<=1000){
            return;
        }
        times = System.currentTimeMillis();
        Intent intent = CommonUtils.getIntent(obj);
        intent.setClass(mContext,cla);
        startActivityForResult(intent,requestCode);
    }

    /**
     * 简单存取数据
     * @param key
     * @param value
     * @return
     */
    public boolean putData(String key,Object value){
        return SharedPreferencesUtil.putData(key,value);
    }
    public <T>T getData(String key,Object value){
        return (T) SharedPreferencesUtil.getData(key,value);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
